package com.longdaji.decoration.ui.main;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.longdaji.decoration.Constants;
import com.longdaji.decoration.DecorationApplication;
import com.longdaji.decoration.R;
import com.longdaji.decoration.base.BaseActivity;
import com.longdaji.decoration.base.BaseFragment;
import com.longdaji.decoration.bean.Account;
import com.longdaji.decoration.data.bean.GoodsCategory;
import com.longdaji.decoration.ui.login.passwordLogin.PasswordLoginActivity;
import com.longdaji.decoration.ui.main.cart.CartFragment;
import com.longdaji.decoration.ui.main.community.CommunityFragment;
import com.longdaji.decoration.ui.main.home.HomeFragment;
import com.longdaji.decoration.ui.main.mine.MineFragment;
import com.longdaji.decoration.utils.LogUtil;
import com.umeng.socialize.UMShareAPI;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;


public class MainActivity extends BaseActivity implements MainContract.View {
    private static final String TAG = MainActivity.class.getSimpleName();
    //    @BindView(R.id.tv_location)
//    TextView mTvLocation;
    @BindView(R.id.vp_main_tab)
    ViewPager mVpMainTab;
    @BindView(R.id.tlyt_main_tab)
    TabLayout mTlytMainTab;
    @Inject
    HomeFragment mHomeFragment;
    @Inject
    CommunityFragment mCommunityFragment;
    @Inject
    CartFragment mCartCFragment;
    @Inject
    MineFragment mMineFragment;
    private ArrayList<BaseFragment> mFragments;
    private String[] mTitles = {"桃心", "购物车", "我的"};
    //private String[] mTitles = {"桃心", "社区", "购物车", "我的"};
    //private int mImages[] = {R.drawable.selector_tab_home, R.drawable.selector_tab_community, R.drawable.selector_tab_cart, R.drawable.selector_tab_mine};
    private int mImages[] = {R.drawable.selector_tab_home, R.drawable.selector_tab_cart, R.drawable.selector_tab_mine};
    private MainTabAdapter mAdapter;
    private Intent homeIntent;

    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

//    public static Account myInfo = new Account();

    public static Intent getStartIntent(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        return intent;
    }

    public static void start(Context context) {
        start(context, null);
    }

    public static void start(Context context, Intent extras) {
        Intent intent = new Intent();
        intent.setClass(context, MainActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (extras != null) {
            intent.putExtras(extras);
        }
        context.startActivity(intent);
    }

    // 注销
    public static void logout(Context context, boolean quit) {
        Intent extra = new Intent();
        extra.putExtra(Constants.EXTRA_APP_QUIT, quit);
        start(context, extra);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LogUtil.d(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setUnBinder(ButterKnife.bind(this));

        sp = DecorationApplication.getInstance().getSharedPreferences(Constants.TAO_XIN, MODE_PRIVATE);
        editor = sp.edit();
        //初始化Fragment
        setUp();

//        getAccount();
        Log.d(TAG, "account : " + Account.getInstance().toString());

    }

    @Override
    protected void onStart() {
        super.onStart();
        LogUtil.d(TAG, "onStart");
        onParseIntent();

    }


    private void getAccount() {
        Intent fromLoginIntent = getIntent();
        if (fromLoginIntent != null) {
            int loginWay = fromLoginIntent.getIntExtra(Constants.LOGIN_WAY, Constants.LOGIN_BY_USERNAME);
            switch (loginWay) {
                case Constants.LOGIN_BY_USERNAME:
                    String username = fromLoginIntent.getStringExtra("username");
                    doGetAccount(username, null);

            }
        }
    }

    private void doGetAccount(String username, String telephone) {
        if (username != null) {
            // TODO: 2018/3/20 0020 通过username获取Account
        } else if (telephone != null) {
            // TODO: 2018/3/20 0020  通过telehphone获取Account
        } else {
            Log.e("mytest", "doGetAccount error");
        }
    }

//    @OnClick({R.id.tv_location})
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.tv_location:
//                startActivity(LocationActivity.getStartIntent(this));
//                break;
//            default:
//                break;
//        }
//    }

    private void setUp() {
        mFragments = new ArrayList<>();
        mFragments.add(mHomeFragment);
        //mFragments.add(mCommunityFragment);
        mFragments.add(mCartCFragment);
        mFragments.add(mMineFragment);
        //ViewPager的适配器
        mAdapter = new MainTabAdapter(getSupportFragmentManager(), mFragments, mTitles);
        mVpMainTab.setAdapter(mAdapter);
        mVpMainTab.setOffscreenPageLimit(4);
        //绑定
        mTlytMainTab.setupWithViewPager(mVpMainTab);
        mTlytMainTab.setTabMode(TabLayout.MODE_FIXED);
        mTlytMainTab.setTabGravity(TabLayout.GRAVITY_FILL);
        //设置自定义视图
        for (int i = 0; i < mTlytMainTab.getTabCount(); i++) {
            TabLayout.Tab tab = mTlytMainTab.getTabAt(i);
            tab.setCustomView(getTabView(i));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtil.d(TAG, "onResume");
        if (homeIntent != null) {
            int id = homeIntent.getIntExtra("id", 0);
            Log.d(TAG, "onResume id=" + id);
            if (id == 2) {
                //mVpMainTab.setCurrentItem(2);
                mVpMainTab.setCurrentItem(1);
            }
            homeIntent = null;
        }


    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtil.d(TAG, "onNewIntent");
        setIntent(intent);
        //为什么从loginActivity过来没有执行onNewIntent
//        onParseIntent();
        homeIntent = intent;


    }

    /**
     * 自定义方法，提供自定义Tab
     *
     * @param position 位置
     * @return 返回Tab的View
     */
    public View getTabView(int position) {
        View v = LayoutInflater.from(this).inflate(R.layout.tab_custom, null);
        TextView textView = (TextView) v.findViewById(R.id.tv_title);
        ImageView imageView = (ImageView) v.findViewById(R.id.iv_icon);
        textView.setText(mTitles[position]);
        imageView.setImageResource(mImages[position]);
        return v;
    }

    @Override
    public void showCategoryList(List<GoodsCategory.SecondCategory> list) {

    }

    private void onParseIntent() {
        Intent intent = getIntent();
        if (intent.hasExtra(Constants.EXTRA_APP_QUIT)) {
            onLogout();
            return;
        } else if (intent.hasExtra(Constants.EXTRA_LOOK)) {
            LogUtil.d(TAG, "111111111");
            if (Account.getInstance() != null)
                Account.setInstance(null);
        }
    }

    private void onLogout() {
        // TODO: 2018/5/6 0006
        // 清理缓存&注销监听
        editor.putString(Constants.AUTO_LOGIN_USERNAME, null);
        editor.putString(Constants.AUTO_LOGIN_PASSWORD, null);
        editor.apply();
        Account.setInstance(null);
        // 启动登录
        PasswordLoginActivity.start(this, null);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        UMShareAPI.get(this).release();
        super.onDestroy();
    }
}
